package com.jyniubi.sms.service.impl;


import com.jyniubi.base.exception.Assert;
import com.jyniubi.base.result.R;
import com.jyniubi.base.result.ResponseEnum;
import com.jyniubi.common.utils.RandomUtils;
import com.jyniubi.common.utils.RegexValidateUtils;
import com.jyniubi.sms.feign.ServiceCoreClient;
import com.jyniubi.sms.properties.SmsProperties;
import com.jyniubi.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    ServiceCoreClient serviceCoreClient;

    @Override
    public void sendSms(String phone) {
        // 1. 判断手机号格式是否正确
        boolean b = RegexValidateUtils.checkCellphone(phone);
        Assert.assertNotTrue(b, ResponseEnum.MOBILE_ERROR);
        // 2. 判断短信是否超过一天3次，短信验证码是否过期
        String countSmsKey = "sms:count:" + phone;
        String intervalSmsKey = "sms:interval:" + phone;
        String countSms = stringRedisTemplate.opsForValue().get(countSmsKey);
        Assert.assertNotTrue(!(StringUtils.isNotBlank(countSms) && Integer.parseInt(countSms) >= 3),
                ResponseEnum.ALIYUN_SMS_COUNT_CONTROL_ERROR);
        Assert.assertNotTrue(!stringRedisTemplate.hasKey(intervalSmsKey),
                ResponseEnum.ALIYUN_SMS_INTERVAL_CONTROL_ERROR);
        //手机号重复注册验证
        R r = serviceCoreClient.checkMobile(phone);
        System.out.println(r);
        Assert.assertTrue(r.getCode() != 0, ResponseEnum.REMOTE_ERROR);
        Assert.assertNotTrue(Boolean.parseBoolean(r.getData().get("flag").toString()), ResponseEnum.MOBILE_EXIST_ERROR);
        String host = SmsProperties.HOST;
        String path = SmsProperties.PATH;
        String method = SmsProperties.METHOD;
        String appcode = SmsProperties.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        //随机生成6位的验证码
        String code = RandomUtils.getSixBitRandom();
        log.info("短信验证码：{}", code);
        bodys.put("content", "code:" + code + "," + "expire_at:" + "10");
        bodys.put("template_id", SmsProperties.TEMPLATEID);
        bodys.put("phone_number", phone);


        try {
            //访问短信接口接收响应信息
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//            Map<String,String> map = JSON.parseObject(result, Map.class);
//            log.info("map:{}",map);
//            //判断短信是否发送成功
//            Assert.assertNotTrue(!(CollectionUtils.isEmpty(map) || !"OK".equals(map.get("status"))),
//                    ResponseEnum.ALIYUN_SMS_ERROR);
            stringRedisTemplate.opsForValue().set("sms:code:" + phone, code, 5, TimeUnit.MINUTES);
            if (!stringRedisTemplate.hasKey(countSmsKey)) {
                stringRedisTemplate.opsForValue().set(countSmsKey, "1", 1, TimeUnit.DAYS);
            } else {
                stringRedisTemplate.opsForValue().increment(countSmsKey);
            }
            stringRedisTemplate.opsForValue().set(intervalSmsKey, "1", 3, TimeUnit.MINUTES);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendMessage(String mobile, String templateId, String money) {
        Map<String, String> headers = new HashMap<String, String>();
        String appcode = SmsProperties.APPCODE;
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "money:" + money + "," + "expire_at:" + "10");
        bodys.put("template_id", SmsProperties.TEMPLATEID);
        bodys.put("phone_number", mobile);
        //访问短信接口接收响应信息
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
//            Map<String,String> map = JSON.parseObject(result, Map.class);
//            log.info("map:{}",map);
//            //判断短信是否发送成功
//            Assert.assertNotTrue(!(CollectionUtils.isEmpty(map) || !"OK".equals(map.get("status"))),
//                    ResponseEnum.ALIYUN_SMS_ERROR);
        stringRedisTemplate.opsForValue().set("sms:code:" + mobile, money, 5, TimeUnit.MINUTES);
    }
}
